package com.sevennotes.classtable.ui.pages.components

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.contentColorFor
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.consumeAllChanges
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import com.sevennotes.classtable.model.ClassItemWithName
import com.sevennotes.classtable.ui.pages.main_screen.ClassItemState
import com.sevennotes.classtable.utils.contentColor
import kotlin.math.roundToInt

@Composable
fun StudentButton(
  modifier: Modifier = Modifier,
  classItem: ClassItemState,
  onClassItemMoved: (ClassItemState, Int, Int) -> Unit,
  onDrag: (ClassItemState, Int, Int) -> Unit,
  onClick: (ClassItemWithName) -> Unit = {},
) {
  var offsetX by remember { mutableStateOf(0f)}
  var offsetY by remember { mutableStateOf(0f)}
  var zIndex by remember { mutableStateOf(1f) }
  val color = classItem.item.studentColor?.let { Color(it) } ?: MaterialTheme.colors.primary
  Box(
    modifier = modifier
      .offset(y = classItem.positionY.dp)
      .height(classItem.classHeight.dp)
      .fillMaxWidth()
      .pointerInput(classItem) {
        detectDragGesturesAfterLongPress(
          onDragEnd = {
            onClassItemMoved(
              classItem,
              offsetX.toDp().value.toInt(),
              offsetY.toDp().value.toInt()
            )
            zIndex = 1.0f
            offsetX = 0f
            offsetY = 0f
          }
        ) { change, dragAmount ->
          change.consume()
          zIndex = 3.0f
          offsetX += dragAmount.x
          offsetY += dragAmount.y
          onDrag(classItem,offsetX.toDp().value.toInt(), offsetY.toDp().value.toInt())
        }
      }
      .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
      .zIndex(zIndex)
      .clickable { onClick(classItem.item) }
      .background(color = color, shape = RoundedCornerShape(5.dp)),
    contentAlignment = Alignment.Center
  ) {
    Text(text = classItem.item.studentName, color = contentColor(color = color))
  }
}
